
import org.osflash.zeroi.logging.LoggerClass;
import org.osflash.zeroi.logging.publisher.Publisher;

import com.mab.util.DebugLight;
import org.osflash.zeroi.logging.LogLevel;


/**
 * A Publisher which connects to XTrace
 * @see	http://www.osflash.org/xtrace
 * You need to start XTrace in advance to make it work
 * based on SOSPublisher class developed by Ralf Bokelberg
 * @author	Jens Krause [www.websector.de]
 * @license LGPL
 *  
 */
 
 
class org.osflash.zeroi.logging.publisher.XTracePublisher extends LoggerClass implements Publisher
{
	private var xTraceDebug: DebugLight;	
	private static var initialized: Boolean = initialize();
	public static var instance: XTracePublisher;
	
	private static function initialize(): Boolean
	{
		if( initialized && instance != undefined) return true;							
		if( LoggerClass == undefined) return false;
		if( DebugLight == undefined) return false;
		
		XTracePublisher.instance = new XTracePublisher();
		LoggerClass.getInstance().addListener( XTracePublisher.instance);
		return true;
	} 
	

	public function XTracePublisher()
	{		
		xTraceDebug = new DebugLight();
		xTraceDebug.initSocket("127.0.0.1");

		LoggerClass.getInstance().replayHistory(this);	
	}
	
	public function publish( type:String, message:String): Void 
	{
		if( message.length == 0) return;
		var xmlMessage:String = convertLevelType(type) + ' ' + message;
		xTraceDebug.trace(xmlMessage);
	}
	
	/**
	* converts Zerois level type to a XTrace level identifier
	* At present XTrace supports only 4 levels
	*/
	private function convertLevelType (type: String): String 
	{
		var level: String;
		switch (type)
		{
			case "debug":
				level = DebugLight.DEBUG;
			break;
			case "warn":
				level = DebugLight.WARN;
			break;			
			case "fatal":
				level = DebugLight.CRITICAL;
			break;				
			default:
				level = DebugLight.NORMAL;
					
		};
		
		return level;
	};
	
	public function toString(): String
	{
		return "[object XTracePublisher]";
	}
	
}